using System;
using System.Text.Json;
using JlPay.Sdk.Core;
using JlPay.Sdk.Services;

namespace JlPay.Sdk.Models
{
    /// <summary>
    /// 标准响应基类
    /// </summary>
    public class StandardResponse
    {
        /// <summary>
        /// 返回码
        /// </summary>
        public string? RetCode { get; set; }
        
        /// <summary>
        /// 返回消息
        /// </summary>
        public string? RetMsg { get; set; }
        
        /// <summary>
        /// 是否成功
        /// </summary>
        public bool IsSuccess() => RetCode is "00000" or "00";
        
        /// <summary>
        /// 获取返回码
        /// </summary>
        public string GetRetCode() => RetCode ?? "";
        
        /// <summary>
        /// 获取返回消息
        /// </summary>
        public string GetRetMsg() => RetMsg ?? "";

        /// <summary>
        /// 处理响应结果并输出到控制台
        /// </summary>
        /// <param name="operationName">操作名称</param>
        /// <param name="config">配置对象</param>
        public void HandleResponse(string operationName, Config? config = null)
        {
            if (IsSuccess())
            {
                Console.WriteLine($"{operationName}成功！");
                // 使用snake_case命名策略序列化，匹配PHP版本的输出格式
                // 注意：这里使用this.GetType()而不是StandardResponse，以确保包含子类的所有属性
                Console.WriteLine("响应报文：" + JsonSerializer.Serialize(this, this.GetType(), new JsonSerializerOptions 
                { 
                    WriteIndented = true,
                    PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                }));
            }
            else
            {
                Console.WriteLine($"{operationName}失败: {RetCode} - {RetMsg}");
            }
        }

        /// <summary>
        /// 处理响应结果（包含异常处理）
        /// </summary>
        /// <param name="operationName">操作名称</param>
        /// <param name="config">配置对象</param>
        /// <param name="exception">异常对象</param>
        public void HandleResponseWithException(string operationName, Config? config = null, Exception? exception = null)
        {
            if (exception != null)
            {
                Console.WriteLine($"{operationName}请求失败: {exception.Message}");
                if (config?.Debug == true)
                {
                    Console.WriteLine($"异常详情: {exception}");
                }
            }
            else
            {
                HandleResponse(operationName, config);
            }
        }
    }
} 